import socket

from irc.client import IRC, DCCConnection, ServerConnection, Event

class ServerConnectionModel(ServerConnection):

    def disconnect(self, message=""):
        """Hang up the connection.

        Arguments:

            message -- Quit message.
        """
        if self.connected:
            self.connected = 0
            self.quit(message)
            try:
                self.socket.shutdown(socket.SHUT_RDWR)
                self.socket.close()
            except socket.error:
                pass
            del self.socket
        self._handle_event(Event("disconnect", self.server, "", [message]))
    

    def process_data(self):
        "read and process input from self.socket"
        try:
            ServerConnection.process_data(self)
        except AttributeError as e:
            # Nonetype with regular expression
            pass


class DCCConnectionModel(DCCConnection):

    def disconnect(self, message=""):
        """Hang up the connection and close the object.

        Arguments:

            message -- Quit message.
        """
        if not self.connected:
            return
        self.connected = 0
        try:
            self.socket.shutdown(socket.SHUT_RDWR)
            self.socket.close()
        except socket.error:
            pass
        del self.socket
        self.irclibobj._handle_event(
            self,
            Event("dcc_disconnect", self.peeraddress, "", [message]))
        self.irclibobj._remove_connection(self)


class IRCModel(IRC):

    def server(self):
        """Creates and returns a ServerConnectionModel object."""
        c = ServerConnectionModel(self)
        with self.mutex:
            self.connections.append(c)
        return c

    def dcc(self, dcctype="chat"):
        """Creates and returns a DCCConnectionModel object.

        Arguments:

            dcctype -- "chat" for DCC CHAT connections or "raw" for
                       DCC SEND (or other DCC types). If "chat",
                       incoming data will be split in newline-separated
                       chunks. If "raw", incoming data is not touched.
        """
        with self.mutex:
            c = DCCConnectionModel(self, dcctype)
            self.connections.append(c)
        return c
